package com.soriya.nestlive.repository

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.soriya.nestlive.model.Live
import com.soriya.nestlive.net.LiveApi
import javax.inject.Inject

class LiveByCategoryPagingRepository @Inject constructor(
    private val liveApi: LiveApi
) : PagingSource<Int, Live>() {

    var categoryId = 0L

    override fun getRefreshKey(state: PagingState<Int, Live>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Live> {
        val next = params.key ?: 1

        val pageSize = 5

        return try {
            val liveList = liveApi.getByCategoryId(categoryId, next, pageSize)

            LoadResult.Page(
                data = liveList.data.list,
                prevKey = null,
                nextKey = if (liveList.data.totalPage > liveList.data.currentPage) liveList.data.currentPage + 1 else null
            )
        } catch (e : Exception) {
            e.printStackTrace()
            LoadResult.Error(e)
        }
    }
}